﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using WUDI.ECharts;

namespace EChartsApp
{
    public static partial class EChartsUtil
    {
        public static StringWriter SW_ECharts = null;
        private static object locker = new object();
        public static string ToEChartsJson(this EChartsOption obj)
        {
            lock (locker)
            {
                SW_ECharts = new StringWriter();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                settings.DateFormatString = "yyyy/MM/dd HH:mm:ss";
                settings.NullValueHandling = NullValueHandling.Ignore;
                settings.Converters.Add(new EChartsConverter(obj.series));
                var writer = new JsonTextWriter(SW_ECharts)
                {
                    //QuoteChar = '\''
                };
                JsonSerializer serializer = JsonSerializer.Create(settings);
                serializer.Serialize(writer, obj);
                writer.Flush();
                var json = SW_ECharts.GetStringBuilder().ToString();

                //忽略空值
                json = System.Text.RegularExpressions.Regex.Replace(json, @"\""[a-z0-9]+\"":null(,|\n)?", "", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                //删除多余逗号
                json = System.Text.RegularExpressions.Regex.Replace(json, @",}", "}", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                return json;
            }
        }


        
    }
}
